/**
 * @Description: 用户状态管理
 * @Author 卞鹏飞 <228443632@qq.com>
 * @create 02/08/24 3:36 PM
 */
import { defineStore } from 'pinia'
import pkg from '@root/package.json'
import { def, eachTree, to } from 'sf-utils2'
// import { aes } from '@shared/utils/secure.js'
import { ElMessage } from 'element-plus'
import { throwError } from '@shared/utils/error'
import demoApi from '@/api/modules/demo'
import useAppStore from '@/store/use-app-store'

// types
import type { IAppStateUserInfo, IAppStateDepartTree, IAppStateDepartTreeItem } from '@root/types/app-store'
import useLayoutStore from '@store/use-layout-store'
import { _getPathLists } from 'sf-utils2/lib/_helperTreeBase.js'
import useMenuStore from '@store/use-menu-store.ts'

const id = 'user-store'
const storageKey = `__persisted__${pkg.name}__${pkg.version}__${id}`

type TAppState = {
  userInfo: IAppStateUserInfo
  token: string
  departTree: IAppStateDepartTree
}

export default defineStore(id, {
  state: () => {
    return {
      token: undefined,

      /**
       * 用户信息
       * @type {IAppStateUserInfo}
       */
      userInfo: {},

      /**
       * 当前登录人所在的部门树
       * @type {IAppStateDepartTree}
       */
      departTree: undefined
    } as TAppState
  },

  getters: {
    /**
     * 判断是否是 第一次登录, 主要是用于第一次进来修改密码
     * @param state
     * @returns {boolean}
     * @private
     */
    _firstLoginFlag(state) {
      return state?.userInfo?.firstLoginFlag == '0'
    },

    /**
     * 当前所在的部门
     * @private
     */
    _curDepartInfo(state) {
      let depart: IAppStateDepartTreeItem = { id: state.userInfo?.deptId }
      let treeCacheObjBy__id = {}
      eachTree({
        tree: state.departTree,
        props: { children: 'children' } as any,
        callbackItem: (item) => {
          treeCacheObjBy__id[item.__id__] = item
          if (item.id == depart.id) {
            depart = item
            return true
          }
        }
      })

      if (depart) {
        depart.__pathIds__ ||= _getPathLists(depart.__id__, '-') || []
        // console.log('depart.__pathIds__', depart.__pathIds__)
        depart.__pathNodes__ ||= depart.__pathIds__.map((v) => treeCacheObjBy__id[v])
        def(depart, '__pathIds__')
        def(depart, '__pathNodes__')
        depart.departNameByPath = depart.__pathNodes__.map((v) => v?.branchName).join('/')
      }
      return depart
    }
  },

  actions: {
    /**
     * 获取用户信息
     * @return {Promise<void>}
     */
    async getUserInfo() {
      const appStore = useAppStore()
      to(appStore.getPublicIp())
      const [res, err] = await to(demoApi.getLoginUserInfo()) // 获取用户信息
      console.log('res', res)
      if (err || res?.code !== 200) {
        const message = err || res?.message || '获取用户信息失败'
        ElMessage.error(message)
        return throwError(`operate`, message)
      }
      this.userInfo = {
        ...(res?.data || {})
        // empName: aes.decrypt(res?.data?.empName),
        // mobile: aes.decrypt(res?.data?.mobile)
      }
    },

    /**
     * 获取当前用户所在的部门
     * @returns {Promise<void>}
     */
    async getUserDeparts() {
      const [res, err] = await to(demoApi.queryBranchByToken())
      if (err || res?.code !== 200) {
        ElMessage.error(res?.message || String(err))
        return throwError(`operate`, `获取部门信息错误`)
      }
      const data = res?.data || []
      if (!data?.length) {
        // 如果部门数据为空
        // ElMessage.warning(`该用户获取部门信息不存在`)
      }
      data.__hasLoaded__ = true // 已经加载过
      this.departTree = data as unknown as TAppState[`departTree`]
      // console.log('departTree', this.departTree)
    },

    /**
     * 清除用户信息
     */
    clearUserInfo() {
      // user
      // this.lastUserInfo = this.userInfo?.id ? { id: this.userInfo?.id, userNick: this.userInfo?.userNick } : undefined // 设置上一次用户信息
      this.token = undefined
      this.userInfo = undefined

      // 菜单
      const menuStore = useMenuStore()
      menuStore.authMenus = undefined // 用户权限菜单信息
      menuStore.authMenuBtnList = undefined // 权限List 最大

      // layout
      const layoutStore = useLayoutStore()
      layoutStore.tabs = []
      layoutStore.tabsActive = undefined
      layoutStore.collapse = undefined
    },

    /**
     * @description: 退出登录
     * @param type 1：手动点击退出登录按钮 0：点击其它提示弹框
     * @return {*}
     */
    async loginOut(type?: 0 | 1) {
      await to(demoApi.loginQuit())
      if (type) {
        this.clearUserInfo()
      } else {
        this.clearUserInfo()
      }

      // 将所有的iframe移除
      const iframes = Array.from(document.querySelectorAll('iframe'))
      if (iframes?.length) {
        iframes.forEach((item) => {
          item.remove()
        })
      }
    }
  },

  persist: window.__POWERED_BY_QIANKUN__
    ? false
    : {
        key: storageKey,
        paths: ['token', 'lastUserInfo'] // undefined 缓存全部
      }
})
